package 线程的学习.生产者消费者模型;

public class Test {
    public static void main(String[] args) {
        Share s1=new Share();
        Producer p1=new Producer(s1);
        Consumer c1=new Consumer(s1);
        p1.start();
        c1.start();
    }
}
class Share{
    private int[] data=new int[10];
    private int pos=0;
//    临界区，向临界区中放入值
    public synchronized void put(int v){
        while(pos>9){
            try{
                System.out.println(Thread.currentThread().getName()+":生产者 等待");
                this.wait();
            }catch (InterruptedException e){}
        }
        data[pos++]=v;
        this.notify();
    }
//    临界区，从共享变量中取值
    public synchronized int get(){
        int value;
        while (pos<=0){
            try {
                System.out.println(Thread.currentThread().getName() + "：消费者 等待");
                this.wait();
            }catch (InterruptedException e){}

        }
        value=data[--pos];
        this.notifyAll();
        return value;
    }

}
class Producer extends Thread{
    private Share s1;
    public Producer(Share s3){
        this.s1=s3;
    }

    @Override
    public void run() {
        for(int i=0;i<100;i++){
            s1.put(i);
            System.out.println("生产者：生产了"+i+"号");
        }
    }
}

class Consumer extends Thread{
    private Share s2;
    public Consumer(Share s4){
        this.s2=s4;
    }
    @Override
    public void run() {
     int v=0;
     for(int i=0;i<100;i++){
         v=s2.get();
         System.out.println("消费者：消费了"+v+"号");
     }
    }
}